package com.meisen.springboot.controller;

import com.meisen.springboot.exception.ServerException;
import com.meisen.springboot.response.ResultEntity;
import com.meisen.springboot.util.Encrypt;
import com.meisen.springboot.util.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * 文件处理类
 * @author meisen
 * 2018-04-19
 */
@Controller
@RequestMapping(path = "/api/file")
public class FileController {

    @Value("${web.upload-path}")
    private String path;

//    @RequestMapping(value="/uploadForm", method = RequestMethod.GET)
//    public String goUploadImg() {
//        //跳转到 templates 目录下的 uploadimg.html
//        return "uploadForm";
//    }

    @RequestMapping(value="/upload", method = RequestMethod.POST)
    public @ResponseBody
    ResultEntity fileUpload(@RequestParam("file") MultipartFile file) {
        String fileName = file.getOriginalFilename();
        String fileExt = fileName.substring(fileName.lastIndexOf('.'), fileName.length());
        String encryptName = Encrypt.encrypt(fileName) + fileExt;
        // 文件路径需要根据上线之后的路径确定
        String filePath = path + encryptName;
        try {
            Path fPath = Paths.get(filePath);
            if (!Files.exists(fPath)){
                Files.createFile(fPath);
            }
            Files.write(fPath, file.getBytes());
        } catch (Exception e) {
            throw new ServerException(1, "上传图片失败");
        }
        //返回json
        return Result.success("/api/image/" + encryptName, "上传成功");
    }

//    private void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
//       File targetFile = new File(filePath);
//       if (!targetFile.exists()) {
//           targetFile.mkdirs();
//       }
//       FileOutputStream outputStream = new FileOutputStream(filePath + fileName);
//        outputStream.write(file);
//        outputStream.flush();
//        outputStream.close();
//    }
}
